package com.android.settings.audio.peq.peq;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.settings.R;
import com.android.settings.audio.peq.skin.SkinManager;
import com.android.settings.audio.peq.user.HibyUser;
import com.android.settings.audio.peq.user.UserManager;
import com.android.settings.audio.peq.util.PhotoUtil;
import com.android.settings.audio.peq.util.SmartPlayerApplication;
import com.android.settings.audio.peq.util.ToastTool;
import com.android.settings.audio.peq.util.ViewUtil;

/**
 * Created by We on 2023/5/30
 */
public class QrTemplate {
    private QrTemplate() {

    }

    private static final class InstanceHolder {
        private static final QrTemplate instance = new QrTemplate();
    }

    public static QrTemplate getInstance() {
        return InstanceHolder.instance;
    }

    //private View layoutQrcode;

    public void init(Activity activity, View layoutQrcode, Integer qrLogoResId, String shareTypeTitle, QrEditTextDialog.ConfirmListener confirmListener) {
        //this.layoutQrcode = layoutQrcode;

        TextView tvQrCustome = layoutQrcode.findViewById(R.id.tv_custom);

        View llToShare = layoutQrcode.findViewById(R.id.ll_to_share);
        //国际版去掉分享
        //llToShare.setVisibility(HiByFunctionTool.isInternational() ? View.GONE : View.VISIBLE);
        layoutQrcode.findViewById(R.id.ll_to_share).setOnClickListener(v -> {
            Bitmap bitmap = ViewUtil.saveViewAsBitmap(layoutQrcode.findViewById(R.id.rl_qr_bitmap));
            if (bitmap == null) return;
            try {
                String name = tvQrCustome.getText().toString();
                shareImage(bitmap, name, activity);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        });
        layoutQrcode.findViewById(R.id.ll_save_qr).setOnClickListener(v -> saveViewAsBitmapToLocal(activity, layoutQrcode.findViewById(R.id.rl_qr_bitmap)));

        if (qrLogoResId != null) {
            ImageView ivQrcodeLogo = layoutQrcode.findViewById(R.id.iv_qrcode_logo);
            ivQrcodeLogo.setImageResource(qrLogoResId);
        }

        View rlQr = layoutQrcode.findViewById(R.id.rl_qr);
        if (rlQr != null) {
            rlQr.setVisibility(View.GONE);
            rlQr.setOnClickListener(v -> showEditTextDialog(activity, activity.getString(R.string.peq_type_custom_text), tvQrCustome.getText().toString(), value -> {
                tvQrCustome.setText(value);
                if (confirmListener != null) return confirmListener.onSubmit(value);
                return true;
            }));
        }
        layoutQrcode.findViewById(R.id.tv_share_cancel).setOnClickListener(v -> {
            if (rlQr != null) rlQr.setVisibility(View.GONE);
        });
        TextView tvShareType = layoutQrcode.findViewById(R.id.tv_share_type);
        if (tvShareType != null) {
            tvShareType.setText(shareTypeTitle);
        }

        SkinManager.get().setImageDrawable(layoutQrcode.findViewById(R.id.ivShare), R.mipmap.peq_ic_share);
        SkinManager.get().setImageDrawable(layoutQrcode.findViewById(R.id.ivSave), R.mipmap.peq_ic_save_photo);
        SkinManager.get().setImageDrawable(layoutQrcode.findViewById(R.id.ivCancel), R.mipmap.peq_ic_reset_nor);
    }

    private void saveViewAsBitmapToLocal(Activity activity, View view) {
        if (null == view) {
            ToastTool.showToast(SmartPlayerApplication.getInstance(), "view is null");
            return;
        }
        Bitmap bitmap = ViewUtil.saveViewAsBitmap(view);
        if (bitmap == null) return;
        PhotoUtil.saveWithPermission(activity, bitmap, REQUEST_CODE_SAVE_IMG, new PhotoUtil.OnSaveCallback() {
            @Override
            public void onSuccess() {
                ToastTool.showToast(SmartPlayerApplication.getInstance(), activity.getString(R.string.peq_save_success));
            }

            @Override
            public void onFailed(Throwable e) {
                String msg = activity.getString(R.string.peq_store_failure);
                if (e != null) {
                    msg += e.getLocalizedMessage();
                }
                ToastTool.showToast(SmartPlayerApplication.getInstance(), msg);
            }
        });
    }

    public void setQrcodeTitle(View layoutQrcode, String title) {
        TextView tvQrCustom = layoutQrcode.findViewById(R.id.tv_custom);
        if (tvQrCustom != null) {
            tvQrCustom.setText(title);
        }
    }

    private QrEditTextDialog editTextDialog;

    public void showEditTextDialog(Activity activity, String title, String value, QrEditTextDialog.ConfirmListener confirmListener) {
        if (editTextDialog != null) {
            editTextDialog.getDialog().dismiss();
            editTextDialog = null;
        }
        editTextDialog = new QrEditTextDialog(activity, title);
        editTextDialog.showDialog(value, confirmListener);
    }

    public void showQrcode(View layoutQrcode, Bitmap qrBitmap) {
        View rlQr = layoutQrcode.findViewById(R.id.rl_qr);
        if (rlQr != null && qrBitmap != null) {
            rlQr.setVisibility(View.VISIBLE);
            ImageView ivQrcode = layoutQrcode.findViewById(R.id.iv_qrcode);
            ivQrcode.setImageBitmap(qrBitmap);

            //the avatar / nickname
            ImageView ivAvatar = layoutQrcode.findViewById(R.id.iv_avatar);
            TextView tvNickname = layoutQrcode.findViewById(R.id.tv_nickname);
            HibyUser hibyUser = UserManager.getInstance().currentActiveUser();
            if (hibyUser != null) {
                tvNickname.setText(hibyUser.name());
//                hibyUser.userCover(new Callback<GetUserCoverResponse>() {
//                    @Override
//                    public void onSuccess(GetUserCoverResponse resp) {
//                        String path = resp.getPath();
//                        ImageLoader.getInstance().displayImage(ImageDownloader.Scheme.FILE.wrap(path), ivAvatar, getDisplayImageOptions());
//                    }
//
//                    @Override
//                    public void onError(Throwable t) {
//                        ivAvatar.setImageResource(R.drawable.list_login_ic_default_icon);
//                    }
//                });
            } else {
                tvNickname.setText("~");
                ivAvatar.setImageResource(R.drawable.peq_ic_album);
            }

            View llUser = layoutQrcode.findViewById(R.id.llUser);
            if (null != llUser) llUser.setVisibility(View.INVISIBLE);
        }
    }

//    private static DisplayImageOptions mOptions;
//
//    private static DisplayImageOptions getDisplayImageOptions() {
//        if (mOptions == null) {
//            mOptions = new DisplayImageOptions.Builder()
//                    .showImageOnLoading(R.drawable.list_login_ic_default_icon)
//                    .showImageOnFail(R.drawable.list_login_ic_default_icon)
//                    .cacheInMemory(false)
//                    .imageScaleType(ImageScaleType.EXACTLY)
//                    .bitmapConfig(Bitmap.Config.ARGB_8888)
//                    .displayer(new SimpleBitmapDisplayer()).handler(new Handler())
//                    .build();
//        }
//        return mOptions;
//    }

    public void onRequestPermissionResult(Activity activity, View layoutQrcode, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_SAVE_IMG) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                saveViewAsBitmapToLocal(activity, layoutQrcode);
                return;
            }
            handlePermissionDenied();
        }
    }

    private void handlePermissionDenied() {
        ToastTool.showToast(SmartPlayerApplication.getInstance(), "denied!");
    }

    public static final int REQUEST_CODE_SAVE_IMG = 0;


    private void shareImage(Bitmap bitmap, String title, Activity mActivity) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(mActivity.getContentResolver(), bitmap, "IMG" + System.currentTimeMillis(), null));
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        mActivity.startActivity(Intent.createChooser(intent, title));
    }
}
